package com.wobito.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wobito.common.constants.BaseResponse;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.constants.TableDataInfo;
import com.wobito.common.utils.ResultUtils;
import com.wobito.common.utils.StringUtils;
import com.wobito.pojo.bean.ConfigData;
import com.wobito.pojo.bean.ConfigType;
import com.wobito.pojo.dto.config.ConfigDataDTO;
import com.wobito.pojo.dto.config.ConfigTypeDTO;
import com.wobito.pojo.enums.IsDeletedEnum;
import com.wobito.pojo.vo.config.*;
import com.wobito.service.IConfigDataService;
import com.wobito.service.IConfigTypeService;
import com.wobito.system.aspect.OperLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 参数配置表 前端控制器
 * </p>
 *
 * @author lambyang
 * @since 2024-07-23
 */
@RestController
@RequestMapping("/manage/configManage")
@Api(tags = "配置管理")
public class ConfigManageController {


    @Autowired
    private IConfigTypeService configTypeService;
    @Autowired
    private IConfigDataService configDataService;

    @GetMapping()
    @ApiOperation(value = "获取配置类型信息列表")
    @OperLog(thing = "获取配置类型信息列表")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse getConfigList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                      @RequestParam(value = "queryName", required = false) String queryName,
                                      @RequestParam(value = "type", required = false) Integer type,
                                      @RequestParam(value = "isDeleted", required = false) Integer isDeleted) {
        TableDataInfo dataInfo = new TableDataInfo();
        PageHelper.startPage(pageNum, pageSize);
        List<ConfigType> configTypes = configTypeService.selectConfigList(new ConfigTypeVO(queryName, type, isDeleted));
        List<ConfigTypeDTO> configTypeDTOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(configTypes)) {
            configTypeDTOS = configTypes.stream().map(config -> {
                ConfigTypeDTO configTypeDTO = BeanUtil.copyProperties(config, ConfigTypeDTO.class);
                return configTypeDTO;
            }).collect(Collectors.toList());
        }
        dataInfo.setRows(configTypeDTOS);
        dataInfo.setTotal(new PageInfo(configTypes).getTotal());
        return ResultUtils.success(dataInfo);
    }

    @GetMapping("/getConfigData")
    @ApiOperation(value = "根据配置类型获取配置数据")
    @OperLog(thing = "根据配置类型获取配置数据")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse getConfigData(@RequestParam(value = "configKey") String configKey) {
        ConfigType configType = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey, configKey));
        if (ObjectUtil.isEmpty(configType)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未查询到配置参数，请检查是否正确");
        }
        List<ConfigDataDTO> configDataDTOS = configDataService.selectConfigList(new ConfigDataVO(configKey));
        return ResultUtils.success(configDataDTOS);
    }

    @GetMapping("/getConfigDefault")
    @ApiOperation(value = "根据配置Key获取默认值")
    @OperLog(thing = "根据配置Key获取默认值")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse getConfigDefault(@RequestParam(value = "key")String key){
        ConfigType configType=configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey,key));
        if (ObjectUtil.isEmpty(configType)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"未查询到相关参数");
        }
        if (StringUtils.isEmpty(configType.getConfigValue())){
            throw new BusinessException(ErrorCode.NULLPARAMS_ERROR,"该key还未配置默认参数");
        }
        return ResultUtils.success(configType.getConfigValue());
    }

    @PutMapping()
    @ApiOperation(value = "添加配置类型信息")
    @OperLog(thing = "添加配置类型信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse addConfig(@Valid @RequestBody AddConfigTypeVO addConfigTypeVO) {
        ConfigType configType = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigName, addConfigTypeVO.getConfigName()).eq(ConfigType::getConfigKey, addConfigTypeVO.getConfigKey()));
        if (ObjectUtil.isNotEmpty(configType)) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "配置名称或键值重复");
        }
        return ResultUtils.success(configTypeService.insertConfigType(addConfigTypeVO));
    }

    @PutMapping("/addConfigData")
    @ApiOperation(value = "添加配置数据信息")
    @OperLog(thing = "添加配置数据信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse addConfigData(@Valid @RequestBody AddConfigDataVO addConfigDataVO) {
        ConfigData configData = configDataService.getOne(new LambdaQueryWrapper<ConfigData>()
                .eq(ConfigData::getConfigLabel, addConfigDataVO.getConfigLabel()).eq(ConfigData::getConfigValue, addConfigDataVO.getConfigValue()).eq(ConfigData::getConfigKey, addConfigDataVO.getConfigKey()));
        if (ObjectUtil.isNotEmpty(configData)) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "配置数据名称或键值重复");
        }
        return ResultUtils.success(configDataService.insertConfigData(addConfigDataVO));
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "启用配置类型信息")
    @OperLog(thing = "启用配置类型信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse enableConfig(@PathVariable("id") Long id) {
        ConfigType configType = configTypeService.getById(id);
        if (configType.getIsDeleted() == IsDeletedEnum.NORMAL.getCode()) {
            throw new BusinessException(ErrorCode.FORBIDDEN, "该配置已经是启用状态");
        }
        return ResultUtils.success(configTypeService.updateById(new ConfigType(id, IsDeletedEnum.NORMAL.getCode())));
    }

    @PostMapping()
    @ApiOperation(value = "修改配置类型信息")
    @OperLog(thing = "修改配置类型信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse updateConfig(@Valid @RequestBody UpdateConfigTypeVO updateConfigTypeVO) {
        ConfigType configType = configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigName, updateConfigTypeVO.getConfigName()));
        if (ObjectUtil.isNotEmpty(configType) && !updateConfigTypeVO.getConfigId().equals(configType.getId())) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "配置名称或键值已存在");
        }
        return ResultUtils.success(configTypeService.updateConfigType(updateConfigTypeVO));
    }

    @PostMapping("/updateConfigData")
    @ApiOperation(value = "修改配置数据信息")
    @OperLog(thing = "修改配置数据信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse updateConfig(@Valid @RequestBody UpdateConfigDataVO updateConfigDataVO) {
        ConfigData configData = configDataService.getOne(new LambdaQueryWrapper<ConfigData>().eq(ConfigData::getConfigLabel, updateConfigDataVO.getConfigLabel()).eq(ConfigData::getConfigValue, updateConfigDataVO.getConfigValue()).eq(ConfigData::getConfigKey, updateConfigDataVO.getConfigKey()));
        if (ObjectUtil.isNotEmpty(configData) && !updateConfigDataVO.getConfigId().equals(configData.getId())) {
            throw new BusinessException(ErrorCode.REPEATPARAMS_ERROR, "配置数据名称或键值已存在");
        }
        return ResultUtils.success(configDataService.updateConfigData(updateConfigDataVO));
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "停用配置类型信息")
    @OperLog(thing = "停用配置类型信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse delConfig(@PathVariable("id") Long id) {
        ConfigType configType = configTypeService.getById(id);
        if (configType.getIsDeleted() == IsDeletedEnum.DELETED.getCode()) {
            throw new BusinessException(ErrorCode.FORBIDDEN, "该配置已经是停用状态");
        }
        return ResultUtils.success(configTypeService.updateById(new ConfigType(id, IsDeletedEnum.DELETED.getCode())));
    }

    @DeleteMapping("/configData/{id}")
    @ApiOperation(value = "删除配置数据信息")
    @OperLog(thing = "删除配置数据信息")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public BaseResponse delConfigData(@PathVariable("id") Long id) {
        return ResultUtils.success(configDataService.removeById(id));
    }
}
